package com.atguigu.filter;
//Transacation 是事务的意思
import com.atguigu.utils.JdbcUtils;

import javax.servlet.*;
import java.io.IOException;

public class TransactionFilter implements Filter {//Filter是javax.servlet包中的,别弄错了 好几个呢

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {//一次性给所有的请求加了mysql事务行为
            filterChain.doFilter(servletRequest,servletResponse);
            JdbcUtils.commitAndClose();
        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtils.rollbackAndClose();
            throw new RuntimeException(e);//这里再抛,就抛给了tomcat服务器,触发web.xml中error-page选项配置的错误页面了
        }
    }

    @Override
    public void destroy() {

    }
}
